require "activerecord"

require "wondercap/lib/deployment/model/area"
require "wondercap/lib/deployment/model/deployment"
require "wondercap/lib/deployment/model/snapshot"

namespace :wondercap do
  default_wondercap_db_path = "/usr/local/wondercap/db/wondercap.db"
  
  before "wondercap:init_multi_configuration", "wondercap:init_database_connection"
  after "wondercap:init_database_connection", "wondercap:process_database_migrations"

  task :init_database_connection do
    db_path = fetch :wondercap_db_path, default_wondercap_db_path
    db_dir = File.dirname(db_path)
    if !File.directory?(db_dir)
      logger.debug { "creating db folder: #{db_dir}" }
      FileUtils.mkdir_p(db_dir)
    end
    
    ActiveRecord::Base.logger = ::Logger.new(logger_device)
    ActiveRecord::Base.logger.level = ::Logger::FATAL - (fetch :sql_verbose, 0).to_i
    
    ActiveRecord::Base.establish_connection(
      :adapter => "sqlite3",
      :dbfile => db_path
    )
  end
  
  task :process_database_migrations do
    ActiveRecord::Migrator.migrate(File.join(File.dirname(__FILE__), "..", "model", "migrations"))
  end
  
  task :nuke_database do
    db_path = fetch(:wondercap_db_path, default_wondercap_db_path)
    logger.debug("nuking the database: #{db_path}")
    FileUtils.rm_rf(db_path)
  end
    
end